import React, { useState } from "react";
import {
  View,
  Text,
  Input,
  Textarea,
  Picker,
  Slider,
  Radio,
  Checkbox,
  Label,
} from "@tarojs/components";
import {
  QuestionConfig,
  Option,
  CompositeField,
} from "../../config/formConfig";
import "./index.scss";

interface FormFieldProps {
  config: QuestionConfig;
  value: any;
  onChange: (value: any) => void;
}

const FormField: React.FC<FormFieldProps> = ({ config, value, onChange }) => {
  const renderTextField = (fieldConfig: QuestionConfig | CompositeField) => {
    // 判断是否为composite类型的子字段
    const isCompositeSubfield =
      config.type === "composite" &&
      config.compositeFields?.some((f) => f.id === fieldConfig.id);

    // 如果是composite类型的子字段，则使用parent value中的子字段值
    const fieldValue = isCompositeSubfield
      ? (value && value[fieldConfig.id]) || ""
      : value || "";

    // 如果是composite类型的子字段，则更新parent value中的子字段值
    const handleInputChange = (newValue: string) => {
      if (isCompositeSubfield) {
        onChange({
          ...value,
          [fieldConfig.id]: newValue,
        });
      } else {
        onChange(newValue);
      }
    };

    return (
      <View className="form-field__text">
        <Input
          placeholder={
            fieldConfig.placeholder || `请输入${fieldConfig.label || ""}`
          }
          value={fieldValue}
          onInput={(e) => handleInputChange(e.detail.value)}
          type={fieldConfig.type === "number" ? "number" : "text"}
          className="form-field__input"
        />
      </View>
    );
  };

  const renderTextareaField = (
    fieldConfig: QuestionConfig | CompositeField
  ) => {
    // 判断是否为composite类型的子字段
    const isCompositeSubfield =
      config.type === "composite" &&
      config.compositeFields?.some((f) => f.id === fieldConfig.id);

    // 如果是composite类型的子字段，则使用parent value中的子字段值
    const fieldValue = isCompositeSubfield
      ? (value && value[fieldConfig.id]) || ""
      : value || "";

    // 如果是composite类型的子字段，则更新parent value中的子字段值
    const handleInputChange = (newValue: string) => {
      if (isCompositeSubfield) {
        onChange({
          ...value,
          [fieldConfig.id]: newValue,
        });
      } else {
        onChange(newValue);
      }
    };

    return (
      <View className="form-field__textarea">
        <Textarea
          placeholder={
            fieldConfig.placeholder || `请输入${fieldConfig.label || ""}`
          }
          value={fieldValue}
          onInput={(e) => handleInputChange(e.detail.value)}
          maxlength={500}
          autoHeight
          className="form-field__textarea-input"
        />
      </View>
    );
  };

  const renderSingleSelect = (fieldConfig: QuestionConfig | CompositeField) => {
    if (!fieldConfig.options) return null;

    // 判断是否为composite类型的子字段
    const isCompositeSubfield =
      config.type === "composite" &&
      config.compositeFields?.some((f) => f.id === fieldConfig.id);

    // 如果是composite类型的子字段，则使用parent value中的子字段值
    const fieldValue = isCompositeSubfield
      ? value && value[fieldConfig.id]
      : value;

    // 如果是composite类型的子字段，则更新parent value中的子字段值
    const handleSelectionChange = (newValue: any) => {
      if (isCompositeSubfield) {
        onChange({
          ...value,
          [fieldConfig.id]: newValue,
        });
      } else {
        onChange(newValue);
      }
    };

    return (
      <View className="form-field__single-select">
        <View className="form-field__options-grid form-field__options-grid--single">
          {fieldConfig.options.map((option) => (
            <View
              key={option.value.toString()}
              className={`form-field__option-item ${
                fieldValue === option.value
                  ? "form-field__option-item--active"
                  : ""
              }`}
              onClick={() => handleSelectionChange(option.value)}
            >
              <View className="form-field__radio-custom">
                <View className="form-field__radio-outer">
                  {fieldValue === option.value && (
                    <View className="form-field__radio-inner" />
                  )}
                </View>
                <View className="form-field__option-text">{option.label}</View>
              </View>
            </View>
          ))}
        </View>
      </View>
    );
  };

  const renderMultiSelect = (fieldConfig: QuestionConfig | CompositeField) => {
    if (!fieldConfig.options) return null;

    // 判断是否为composite类型的子字段
    const isCompositeSubfield =
      config.type === "composite" &&
      config.compositeFields?.some((f) => f.id === fieldConfig.id);

    // 如果是composite类型的子字段，则使用parent value中的子字段值
    const fieldValue = isCompositeSubfield
      ? (value && value[fieldConfig.id]) || []
      : value || [];

    const selectedValues = Array.isArray(fieldValue) ? fieldValue : [];

    const handleChange = (optionValue: any) => {
      const newValue = [...selectedValues];
      const index = newValue.indexOf(optionValue);

      if (index > -1) {
        newValue.splice(index, 1);
      } else {
        newValue.push(optionValue);
      }

      if (isCompositeSubfield) {
        onChange({
          ...value,
          [fieldConfig.id]: newValue,
        });
      } else {
        onChange(newValue);
      }
    };

    return (
      <View className="form-field__multi-select">
        <View className="form-field__options-grid form-field__options-grid--single">
          {fieldConfig.options.map((option) => {
            const isChecked = selectedValues.includes(option.value);

            return (
              <View
                key={option.value.toString()}
                className={`form-field__option-item ${
                  isChecked ? "form-field__option-item--active" : ""
                }`}
                onClick={() => handleChange(option.value)}
              >
                <View className="form-field__checkbox-custom">
                  <View className="form-field__checkbox-outer">
                    {isChecked && (
                      <View className="form-field__checkbox-inner" />
                    )}
                  </View>
                  <View className="form-field__option-text">
                    {option.label}
                  </View>
                </View>
              </View>
            );
          })}
        </View>
      </View>
    );
  };

  const renderDateField = () => {
    // Convert current date to array format for Taro Picker
    const now = new Date();
    const formattedValue = value
      ? value.split("-")
      : [
          now.getFullYear(),
          (now.getMonth() + 1).toString().padStart(2, "0"),
          now.getDate().toString().padStart(2, "0"),
        ];

    return (
      <View className="form-field__date">
        <Picker
          mode="date"
          value={value || ""}
          onChange={(e) => {
            const selectedDate = e.detail.value;
            onChange(selectedDate);
          }}
        >
          <View className="form-field__date-selector">
            <Text className="form-field__date-text">
              {value || "请选择日期"}
            </Text>
          </View>
        </Picker>
      </View>
    );
  };

  const renderSingleSlider = (fieldConfig: QuestionConfig) => {
    const min = fieldConfig.min || 0;
    const max = fieldConfig.max || 100;
    const step = fieldConfig.step || 1;
    const currentValue = value !== undefined ? value : min;

    return (
      <View className="form-field__single-slider">
        <View className="form-field__slider-value">
          当前值:{" "}
          <Text className="form-field__slider-highlight">{currentValue}</Text>
        </View>

        <Slider
          min={min}
          max={max}
          step={step}
          value={currentValue}
          blockSize={28}
          activeColor="#fe2c55"
          backgroundColor="rgba(255, 255, 255, 0.2)"
          blockColor="#fff"
          onChanging={(e) => onChange(e.detail.value)}
        />
      </View>
    );
  };

  const renderDoubleSlider = (fieldConfig: QuestionConfig) => {
    // Taro doesn't have a native range slider, so we'll use two sliders
    const min = fieldConfig.min || 0;
    const max = fieldConfig.max || 100;
    const step = fieldConfig.step || 1;
    const currentValues = Array.isArray(value) ? value : [min, max];

    return (
      <View className="form-field__double-slider">
        <View className="form-field__slider-row">
          <Slider
            min={min}
            max={max}
            step={step}
            value={currentValues[0]}
            blockSize={28}
            activeColor="#fe2c55"
            backgroundColor="rgba(255, 255, 255, 0.2)"
            blockColor="#fff"
            onChange={(e) => onChange([e.detail.value, currentValues[1]])}
          />
        </View>
        <View className="form-field__slider-row">
          <Slider
            min={min}
            max={max}
            step={step}
            value={currentValues[1]}
            blockSize={28}
            activeColor="#fe2c55"
            backgroundColor="rgba(255, 255, 255, 0.2)"
            blockColor="#fff"
            onChange={(e) => onChange([currentValues[0], e.detail.value])}
          />
        </View>
        <View className="form-field__slider-value">
          当前范围:{" "}
          <Text className="form-field__slider-highlight">
            {currentValues[0]}
          </Text>{" "}
          -{" "}
          <Text className="form-field__slider-highlight">
            {currentValues[1]}
          </Text>
        </View>
      </View>
    );
  };

  const renderLocationField = () => {
    // 判断是否为composite类型的子字段
    const isCompositeSubfield =
      config.type === "composite" &&
      config.compositeFields?.some((f) => f.type === "location");

    // 如果是composite类型的子字段，我们需要找到它的ID
    let fieldId = "";
    if (isCompositeSubfield) {
      const locationField = config.compositeFields?.find(
        (f) => f.type === "location"
      );
      if (locationField) {
        fieldId = locationField.id;
      }
    }

    // 如果是composite类型的子字段，则使用parent value中的子字段值
    const fieldValue =
      isCompositeSubfield && fieldId
        ? (value && value[fieldId]) || ""
        : value || "";

    // 如果是composite类型的子字段，则更新parent value中的子字段值
    const handleLocationChange = (newValue: any) => {
      if (isCompositeSubfield && fieldId) {
        onChange({
          ...value,
          [fieldId]: newValue,
        });
      } else {
        onChange(newValue);
      }
    };

    // Simple text input as placeholder for location picker
    return (
      <View className="form-field__date">
        <Picker
          mode="region"
          level="city"
          value={fieldValue}
          onChange={(e) => {
            const selectedCity = e.detail.value;
            handleLocationChange(selectedCity);
          }}
        >
          <View className="form-field__date-selector">
            <Text className="form-field__date-text">
              {fieldValue || "请选择地区"}
            </Text>
          </View>
        </Picker>
      </View>
    );
  };

  const renderCompositeField = () => {
    if (!config.compositeFields) return null;

    const compositeValues = value || {};

    return (
      <View className="form-field__composite">
        {config.compositeFields.map((field) => {
          // Check if this field depends on another field
          if (field.dependsOn) {
            const dependsOnValue = compositeValues[field.dependsOn.questionId];
            const isValueMatch = Array.isArray(field.dependsOn.value)
              ? field.dependsOn.value.includes(dependsOnValue)
              : dependsOnValue === field.dependsOn.value;

            if (!isValueMatch) return null;
          }

          return (
            <View key={field.id} className="form-field__composite-item">
              {field.label && (
                <View className="form-field__label">{field.label}</View>
              )}

              {field.type === "text" &&
                !field.multiLine &&
                renderTextField(field)}
              {field.type === "text" &&
                field.multiLine &&
                renderTextareaField(field)}
              {field.type === "number" && renderTextField(field)}
              {field.type === "single-select" && renderSingleSelect(field)}
              {field.type === "multi-select" && renderMultiSelect(field)}
              {field.type === "location" && renderLocationField()}

              {field.type === "text" && field.isInputGroup && (
                <View className="form-field__input-group">
                  <Input
                    placeholder={field.placeholder || "请输入"}
                    value={compositeValues[field.id] || ""}
                    onInput={(e) => {
                      onChange({
                        ...compositeValues,
                        [field.id]: e.detail.value,
                      });
                    }}
                    className="form-field__input"
                  />
                </View>
              )}
            </View>
          );
        })}
      </View>
    );
  };

  const renderField = () => {
    // First check if the field should be displayed based on dependsOn condition
    if (config.dependsOn) {
      // This would need access to the parent formData, which we don't have directly here
      // In a real implementation, this would need to be handled
      // For now, we'll just render the field
    }

    switch (config.type) {
      case "text":
        return config.multiLine
          ? renderTextareaField(config)
          : renderTextField(config);
      case "number":
        return renderTextField(config);
      case "single-select":
        return renderSingleSelect(config);
      case "multi-select":
        return renderMultiSelect(config);
      case "date":
        return renderDateField();
      case "single-slider":
        return renderSingleSlider(config);
      case "double-slider":
        return renderDoubleSlider(config);
      case "location":
        return renderLocationField();
      case "composite":
        return renderCompositeField();
      default:
        return <View>Unsupported field type: {config.type}</View>;
    }
  };

  return (
    <View className="form-field">
      <View className="form-field__header">
        <Text className="form-field__label">{config.label}</Text>
        {config.required && <Text className="form-field__required">*</Text>}
      </View>
      {renderField()}
    </View>
  );
};

export default FormField;
